package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {

    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 查询套餐
     *
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal() {
        List<Setmeal> setmeals = null;
        String SetmealJson = null;
        /**
         * 调用查询全部数据前先判断redis数据库，
         * 如果存在数据则直接取出redis中的数据，反之则查询数据
         */

        try (Jedis jedis = jedisPool.getResource()) {
//            取出redis中的值，并作判断使用
            SetmealJson = jedis.get("Setmeal");
//            判断redis是否有值
            if (null == jedis.get("Setmeal")) {
                //rpc调用查询所有套餐
                setmeals = setMealService.findAll();
                //将setmeals转换为json格式
                SetmealJson = JSON.toJSON(setmeals).toString();
//                查询数据存在redis中
                jedis.set("Setmeal", SetmealJson);
            }
            setmeals = JSONObject.parseArray(SetmealJson, Setmeal.class);
        }
        return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS, setmeals);
    }

    @GetMapping("/findById")
    public Result findById(Integer id) {
        //rpc调用查询数据
        Setmeal setmeal = setMealService.findById(id);
        //返回
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, setmeal);
    }
}
